import { useState,useEffect } from 'react'
import { useNavigate,useLocation } from 'react-router-dom'
import { Form, Input, Button, NavBar, Toast } from 'react-vant'
import './style/newUser.css'
import { handleAddUser1 } from '../../utils/api'
const NewUser:React.FC = () => {
    const navigate = useNavigate()
    const location = useLocation()
    const email = location.state?.email
    const [form] = Form.useForm();
    const [isLoading, setIsLoading] = useState(false)
    const [formValues, setFormValues] = useState({
        username:"",
        password:"",
        confirmPassword: ''
    })
    const [showPassword, setShowPassword] = useState({
        password: false,
        confirmPassword: false
    });
    const YanZhen = (value: string) => {
        const guize = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[/*\-+.])[A-Za-z\d/*\-+.]{8,}$/
        const values = guize.test(value)
        console.log(values,'values');
        if (values) {
            return true
        } else {
            return false
        }
    }
    const onFinish = async () => {
        if ( !formValues.username ||!formValues.password ||!formValues.confirmPassword) return
        try{
            setIsLoading(true)
            Toast.loading({
                message: '正在注册...',
                forbidClick: true,  
                duration: 3000,
            })
            const params={
                username: formValues.username,
                password: formValues.password,
                confirmPassword: formValues.confirmPassword,
                email:email
            }
            let res = await handleAddUser1(params)
            if( res.data.code  === 200){
                Toast.success({
                    message:"注册成功",
                    forbidClick:true,
                })
                await new Promise((resolve) => { setTimeout(resolve, 1000) })
                navigate('/info')
            }else{
                // 显示错误提示，2秒后自动消失
             Toast.fail({
              message:res.data.message || '网络错误，请重试',
              forbidClick:true,
              duration:2000,
             })
          }
        }catch(err){
            console.log(err,'err');
            
        } finally{
            setIsLoading(false)
        }
    }
    const onValuesChange = (values:any) => {
        setFormValues({...formValues,...values})
        console.log(values,'1')
    }
    useEffect(()=>{
        console.log('====================================');
        console.log(email,'email');
        console.log('====================================');
    },[])
    return(
        <>
            <div className="yanzheng-box">
                <NavBar
                    title="创建一个账户"
                    onClickLeft={() => {
                        navigate('/yanzheng') 
                    }}
                />
                <div className="yanzheng-content">
                      <Form
                        form={form}
                        onFinish={onFinish}
                        onValuesChange={onValuesChange}
                        footer={
                            <div style={{ margin: '16px 16px 0' }}>
                                <Button round nativeType='submit' type='primary' block
                                    loading={isLoading}
                                    disabled={!YanZhen(String(formValues.confirmPassword))}
                                >
                                    继续
                                </Button>
                            </div>
                        }
                    >
                        <span className="parentBox-span">用户名</span>
                        <Form.Item
                            name='username'
                            rules={[{ required: true, message: '请输入正确用户名' }]}
                        >
                            <Input placeholder='输入用户名' className="parentBox-input" />
                        </Form.Item>
                        <Form.Item
                            name='password'
                            rules={[{ pattern:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[/*\-+.])[A-Za-z\d/*\-+.]{8,}$/, message: '请输入正确密码' }]}
                        >
                            <Input 
                            placeholder='输入您的密码' 
                            className="parentBox-input" 
                            type={showPassword.password ? 'text' : 'password'}
                            />
                        </Form.Item>
                        <span className="parentBox-span1">密码至少包含8个字符</span>
                        <Form.Item
                            name='confirmPassword'
                            rules={[{ message: '请输入正确的验证码' },
                                ({ getFieldValue }) => ({
                                    validator(_, value) {
                                        if (!value || getFieldValue('password') === value) {
                                            return Promise.resolve();
                                        }
                                        return Promise.reject(new Error('请确认两次输入的密码是否一致'));
                                    },
                                }),
                            ]}
                        >
                            <Input 
                            placeholder='输入您的密码' 
                            className="parentBox-input" 
                            type={showPassword.password ? 'text' : 'password'}
                            />
                        </Form.Item>
                        <span className="parentBox-span1">密码至少包含8个字符</span>
                    </Form>
                </div>
               
            </div>
        </>
    )
}
export default NewUser